/**
 * 获取题目是否支持机阅
 * @param {*} param0
 */
export const getAnswerScoreable = ({ stem = {}, answer = {} }) => {
  if (!stem || typeof stem === 'string') return 0

  const { sqs = [], type } = stem

  const checkSqs = (sqs) => {
    const answerScoreable = sqs.every((i) => {
      const { type } = i
      if (type === '选择题') {
        return true
      } else {
        return false
      }
    })

    return answerScoreable ? 1 : 0
  }

  if (Array.isArray(sqs) && sqs.length > 0) {
    return checkSqs(sqs)
  } else {
    if (type === '选择题') {
      try {
        if (answer.anSqs.length === 1) {
          return 1
        } else {
          return 0
        }
      } catch (error) {
        return 1
      }
    } else {
      return 0
    }
  }
}

/**
 * 格式化题干
 * @param {*} stem 题干
 * @param {*} options 选项
 * @returns
 */
export const formatQuestionStem = (stem, options = {}) => {
  const { label } = options

  function Stem(data) {
    const { html, og, sqs, type, label = '' } = data
    this.html = html
    this.og = og
    this.sqs = sqs
    this.type = type
    this.label = label
  }

  if (typeof stem === 'string') {
    const { type } = options
    return new Stem({
      html: stem,
      og: null,
      sqs: [],
      type,
      label
    })
  } else {
    const { html, og, sqs = [], type } = stem
    return new Stem({
      html,
      og,
      sqs: Array.isArray(sqs) && sqs.length > 0 ? sqs.map((i) => new Stem(i)) : sqs,
      type,
      label
    })
  }
}

/**
 * 生成答案
 * @param {*} param0
 * @returns
 */
export const generateStudentAnswer = ({
  anSqs = [],
  anSqsIndex = 0,
  ansIndex = 0,
  answer = '',
  init = null
}) => {
  if (init) {
    const { anSqs } = init

    try {
      const deepCopy = (data) => JSON.parse(JSON.stringify(data))

      return {
        anSqs: deepCopy(anSqs).map((anSqsItem) => {
          if (Array.isArray(anSqsItem)) {
            anSqsItem = anSqsItem.map((item) => {
              item.ans = item.ans.map((ansItem) => {
                return {
                  anStudent: ''
                }
              })

              return item
            })
          } else {
            anSqsItem.ans = anSqsItem.ans.map((ansItem) => {
              return {
                anStudent: ''
              }
            })
          }

          return anSqsItem
        })
      }
    } catch (error) {
      return ''
    }
  }

  let anSqsItem = anSqs[anSqsIndex]

  if (!anSqsItem) {
    anSqs[anSqsIndex] = {
      ans: []
    }
    anSqsItem = anSqs[anSqsIndex]
  }

  const obj = {}
  answer.search(/[a-zA-z]+:\/\/[^\s]*/, '') != -1
    ? (obj['anStudentUrl'] = answer)
    : (obj['anStudent'] = answer)
  anSqsItem.ans[ansIndex] = obj

  for (let i = 0; i < anSqsIndex; i++) {
    let _anSqsItem = anSqs[i]
    if (!_anSqsItem) {
      anSqs[i] = {
        ans: [
          {
            anStudent: ''
          }
        ]
      }
    }
  }

  return { anSqs }
}

/**
 * 格式化答案
 * @param {*} answer
 * @returns
 */
export const formatQuestionAnswer = (answer) => {
  if (typeof answer === 'string') {
    answer = JSON.parse(answer)
  }

  const anSqs = answer.anSqs

  if (!anSqs) return

  return {
    anSqs: anSqs.map((anSqsItem) => {
      return {
        ans: anSqsItem.ans.map((ansItem) => {
          const { html } = ansItem

          if (!html) return ansItem

          const anStudent = html
            .replace(/<span[\w\W]+?>/, '')
            .replace('</span>', '')
            .replace(/<[\w\W]*?>/gi, '') // 清空剩余html标签
          return {
            anStudent
          }
        })
      }
    })
  }
}

/**
 * 生成英语听说题目
 * @param {*} question
 * @returns
 */
export const generateEnglishQuestions = (data) => {
  const { questions = null, questionTypes = [] } = data

  const newQuestions = []

  // 题目来源类型判断
  questions.forEach((item) => {
    if (/^ky-/.test(item.questionId)) {
      item.sourceType = '10086' // 英语听说
    }
  })

  /**
   * 生成听后选择题
   * @param {*} questions 题目列表
   * @returns
   */
  const genChooseQuestion = (questions = []) => {
    const stem = {
      structure_type: 'collector.choose',
      info: {
        question: questions
      }
    }

    let answerAnSqs = []
    questions.forEach((q) => {
      const { anSqs = [] } = JSON.parse(q.answer)

      answerAnSqs.push([...anSqs])
    })
    const answer = {
      anSqs: answerAnSqs
    }

    return {
      answer: JSON.stringify(answer),
      courseId: 10086,
      questionId: null,
      questionIds: questions.map((q) => q.questionId),
      questionSort: null,
      sourceType: '10086',
      stem: JSON.stringify(stem),
      typeId: '1008601'
    }
  }

  /**
   * 生成听后转述并记录题
   * @param {*} questions 题目列表
   * @returns
   */
  const genFillAndPictureQuestion = (questions = []) => {
    const stem = {
      structure_type: 'collector.fill_picture',
      info: {
        question: questions
      }
    }

    let answerAnSqs = []
    questions.forEach((q) => {
      const { anSqs = [] } = JSON.parse(q.answer)

      answerAnSqs.push([...anSqs])
    })
    const answer = {
      anSqs: answerAnSqs
    }

    return {
      answer: JSON.stringify(answer),
      courseId: 10086,
      questionId: null,
      questionIds: questions.map((q) => q.questionId),
      questionSort: null,
      sourceType: '10086',
      stem: JSON.stringify(stem),
      typeId: '1008606'
    }
  }

  questionTypes.forEach((type = {}) => {
    const { structure_type, roundNum } = type
    const questionIds = Array.from(type.questionIds)

    while (questionIds.length > 0) {
      const ids = questionIds.splice(0, roundNum)
      const questionGroup = questions.filter((q) => ids.includes(q.questionId))

      switch (structure_type) {
        case 'collector.choose':
          newQuestions.push(genChooseQuestion(questionGroup))
          break
        case 'collector.fill':
          questionGroup.forEach((question) => {
            const { lastQuestionId: pictureQuestionId } = question

            const success = questions.some((q, index) => {
              if (q.questionId === pictureQuestionId) {
                newQuestions.push(
                  genFillAndPictureQuestion([question, questions.splice(index, 1)[0]])
                )
                return true
              } else {
                return false
              }
            })

            if (!success) newQuestions.push(question)
          })
          break
        case 'collector.picture':
          questionGroup.forEach((question) => {
            const { lastQuestionId: fillQuestionId } = question

            const success = questions.some((q, index) => {
              if (q.questionId === fillQuestionId) {
                newQuestions.push(
                  genFillAndPictureQuestion([questions.splice(index, 1)[0], question])
                )
                return true
              } else {
                return false
              }
            })

            if (!success) newQuestions.push(question)
          })
          break
        default:
          newQuestions.push(...questionGroup)
          break
      }
    }
  })

  return newQuestions
}

/**
 * 菁优网题目格式转换为学科网题目格式
 * @param {*} question
 * @returns
 */
export const jywConvertToXkw = (question) => {
  const { typeName, typeId, options, answer, displayAnswer, explanation, method, discuss } =
    question
  let { stem } = question

  if (['选择题', '多选题'].includes(typeName)) {
    // 选择题
    let stemHtml = ''
    const stemOptions = JSON.parse(options)
    let stemOptionsHtml = ''
    if (Array.isArray(stemOptions)) {
      stemOptions.forEach((option, index) => {
        stemOptionsHtml += `<td>${'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(
          index
        )}.&nbsp;<span class=\"qml-op\"><span>${option}</span></span></td>`
      })
    }

    // 兼容table标签
    try {
      let stemTableBefore = stem.match(/[\w\W]*?<\/table>/)[0]
      let stemTableAfter = stem.replace(stemTableBefore, '')

      if (stemTableBefore) {
        stemTableBefore = stemTableBefore.replace('<table', '<table style="margin:0.1rem 0"')
        stem = stemTableBefore
      }

      if (stemTableAfter) {
        stem += `<div style="display: inline">${stemTableAfter}</div>`
      }
    } catch {}

    if (stem.indexOf('MathJye') != -1) {
      stemHtml = `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem">${stem}</fieldset>`
    } else {
      stemHtml = `<p>${stem}</p>`
    }
    const displayAnswer = JSON.parse(answer)
      .map((item) => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(parseInt(item)))
      .join('')

    question.stem = `<div class=\"qml-stem\" data-copyright=\"jyeoo.com\">${stemHtml}<div class=\"qml-og\"><table style=\"width:100%\"class=\"qml-og\"><tbody><tr>${stemOptionsHtml}</tr></tbody></table></div></div>`
    question.answer = `<div class=\"qml-answer\" data-copyright=\"jyeoo.com\"><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>${displayAnswer}</p></span></span></div>`
    // 解析
    question.explanation = `<div class=\"qml-explanation\" style=\"line-height: 0.28rem;\" data-copyright=\"jyeoo.com\"><div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${
      explanation ? explanation : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${
      method ? method : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${
      discuss ? discuss : '无'
    }</div></div></div>`
  } else if (typeId === 'jyw-27-6') {
    // 英语 -> 阅读理解
    // 生成题干
    const generateStem = () => {
      try {
        let remainStem = stem
        let stemHtmlTemp
        let stemHtml // 大题题干
        const stemSqs = [] // 小题数组
        if (stem.match(/[\w\W]*?<br \/>（1）/)) {
          stemHtmlTemp = stem.match(/[\w\W]*?<br \/>（1）/)[0].replace('<br />（1）', '')
        } else if (stem.match(/[\w\W]*?<\/table>（1）/)) {
          stemHtmlTemp = stem
            .match(/[\w\W]*?<\/table>（1）/)[0]
            .replace('</table>（1）', '</table>')
        } else {
          stemHtmlTemp = ''
        }

        stemHtml =
          `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem;white-space: normal;">${
            stemHtmlTemp.indexOf('&nbsp;&nbsp;') != -1
              ? `<span sytle="white-space: break-spaces;">&nbsp;&nbsp;&nbsp;&nbsp;</span>${stemHtmlTemp}` // 首行缩进
              : stemHtmlTemp
          }</fieldset>`.replace('<br /></fieldset>', '</fieldset>')

        if (!stemHtml) {
          throw new Error('Regexp Match Error')
        }

        remainStem = remainStem.replace(stemHtmlTemp, '') // 小题字符串
        // 从小题字符串提取小题
        const sqsItems = remainStem.split(/<br \/>（[0-9]+）/g)
        let sqsCount = 1 // 小题题号，累加
        sqsItems.forEach((sqsItem) => {
          if (sqsItem) {
            let sqsItemStem = sqsItem.match(/[\w\W]*?<br \/>/)
              ? sqsItem.match(/[\w\W]*?<br \/>/)[0]
              : '' // 小题题干
            let sqsItemStemOptionsHtml = '' // 小题选项

            if (!sqsItemStem) {
              const displayAnswer = JSON.parse(answer)
              const isTrueOrFalseQuestion = displayAnswer.every((item) => {
                if (item === 'T' || item === 'F') {
                  return true
                } else {
                  return false
                }
              })

              if (isTrueOrFalseQuestion) {
                // 判断题
                sqsItemStem = sqsItem
                sqsItemStemOptionsHtml += `<td>A.&nbsp;<span class=\"qml-op\" data-answer=\"T\"><span style=\"font-family: 'Times New Roman' ;\">T</span></span></td>`
                sqsItemStemOptionsHtml += `<td>B.&nbsp;<span class=\"qml-op\" data-answer=\"F\"><span style=\"font-family: 'Times New Roman' ;\">F</span></span></td>`
              } else {
                throw new Error('Regexp Match Error')
              }
            } else {
              const sqsItemStemOptionsTemp = sqsItem.replace(sqsItemStem, '')
              const sqsItemStemOptions = sqsItemStemOptionsTemp.split('<br />')

              sqsItemStemOptions.forEach((item) => {
                if (item) {
                  const [letter, content] =
                    item.split('．').length === 1 ? item.split('.') : item.split('．')
                  sqsItemStemOptionsHtml += `<td>${letter}.&nbsp;<span class=\"qml-op\"><span style=\"font-family: 'Times New Roman' ;\">${content}</span></span></td>`
                }
              })
            }

            stemSqs.push(
              `<div class=\"qml-sq\"><div class=\"qml-stem\"><fieldset style=\"white-space:normal\">${sqsCount++}.${sqsItemStem}</fieldset><div class=\"qml-og\"><table style=\"width:100%\" class=\"qml-og\"><tbody><tr>${sqsItemStemOptionsHtml}</tr></tbody></table></div></div></div>`
            )
          }
        })

        return `
        <div class=\"qml-stem\" data-copyright=\"jyeoo.com\">${stemHtml}${stemSqs.join('')}</div>
        `
      } catch (error) {
        // console.error(error)
        return ''
      }
    }

    // 生成答案
    const generateAnswer = () => {
      try {
        const displayAnswer = JSON.parse(answer)
        const answerItem = []
        displayAnswer.forEach((item) => {
          answerItem.push(
            `<span class="qml-an-sq"><span class="qml-an"><p>${item}</p></span></span>`
          )
        })

        return `<div class="qml-answer" data-copyright=\"jyeoo.com\">${answerItem.join('')}</div>`
      } catch (error) {
        return ''
      }
    }

    const questionStem = generateStem()
    const questionAnswer = generateAnswer()
    if (questionStem && questionAnswer) {
      question.stem = questionStem
      question.answer = questionAnswer
    } else {
      let stemHtml = ''

      if (stem.indexOf('MathJye') != -1 || stem.indexOf('quizPutTag') != -1) {
        stemHtml = `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem">${stem}</fieldset>`
      } else {
        stemHtml = `<p>${stem}</p>`
      }

      question.stem = `<div class=\"qml-stem\" data-copyright=\"jyeoo.com\">${stemHtml}</div>`
      question.answer = `<div class=\"qml-answer\" data-copyright=\"jyeoo.com\"><span class=\"qml-an-sq\"><span class=\"qml-an\">B</span></span><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>D</p></span></span><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>B</p></span></span><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>B</p></span></span><span class=\"qml-an-sq\"><span class=\"qml-an qml-isop \">C</span></span></div>`
    }
    // 解析
    question.explanation = `<div class=\"qml-explanation\" style=\"line-height: 0.28rem;\" data-copyright=\"jyeoo.com\"><div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${
      explanation ? explanation : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${
      method ? method : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${
      discuss ? discuss : '无'
    }</div></div></div>`
  } else if (typeId === 'jyw-27-23' || typeId === 'jyw-27-5') {
    // 英语 -> 语法选择/完形填空
    // 生成题干
    const generateStem = () => {
      try {
        const stemSqsHtml = stem.match(/<table[\w\W]*table>/)
          ? stem.match(/<table[\w\W]*<\/table>/)[0]
          : '' // 小题字符串

        if (!stemSqsHtml) {
          throw new Error('Regexp Match Error')
        }

        const stemHtmlTemp = stem.replace(stemSqsHtml, '')
        const stemHtml =
          `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem;white-space:normal">${
            '&nbsp;&nbsp;&nbsp;&nbsp;' + stemHtmlTemp
          }</fieldset>`.replace('<br /></fieldset>', '</fieldset>') // 大题题干
        const stemSqs = [] // 格式化后的小题
        const stemSqsTemp = stemSqsHtml.match(/<tr>[\w\W]*?<\/tr>/g)
        // 从小题字符串提取小题
        let sqsCount = 1 // 小题题号，累加
        stemSqsTemp.forEach((item) => {
          const sqsItemStemOptions = item
            .replace(/<td>（[0-9]+）<\/td>/g, '')
            .match(/<td[\w\W]*?td>/g)
          let sqsItemStemOptionsHtml = ''
          sqsItemStemOptions.forEach((item) => {
            if (item) {
              const [letter, content] =
                item.split('．').length === 1 ? item.split('.') : item.split('．')
              sqsItemStemOptionsHtml += `<td>${letter}.&nbsp;<span class=\"qml-op\"><span style=\"font-family: 'Times New Roman' ;\">${content}</span></span></td>`
            }
          })
          stemSqs.push(
            `<div class=\"qml-sq\"><div class=\"qml-stem\"><fieldset style=\"white-space:normal\">${`（${sqsCount++}）`}</fieldset><div class=\"qml-og\"><table style=\"width:100%\" class=\"qml-og\"><tbody><tr>${sqsItemStemOptionsHtml}</tr></tbody></table></div></div></div>`
          )
        })

        return `
        <div class=\"qml-stem\" data-copyright=\"jyeoo.com\">${stemHtml}${stemSqs.join('')}</div>
        `
      } catch (error) {
        // console.error(error)
        return ''
      }
    }

    // 生成答案
    const generateAnswer = () => {
      try {
        const displayAnswer = JSON.parse(answer)
        const answerItem = []
        displayAnswer.forEach((item) => {
          answerItem.push(
            `<span class="qml-an-sq"><span class="qml-an"><p>${item}</p></span></span>`
          )
        })

        return `<div class="qml-answer" data-copyright=\"jyeoo.com\">${answerItem.join('')}</div>`
      } catch (error) {
        return ''
      }
    }

    const questionStem = generateStem()
    const questionAnswer = generateAnswer()
    if (questionStem && questionAnswer) {
      question.stem = questionStem
      question.answer = questionAnswer
    } else {
      let stemHtml = ''

      if (stem.indexOf('MathJye') != -1 || stem.indexOf('quizPutTag') != -1) {
        stemHtml = `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem">${stem}</fieldset>`
      } else {
        stemHtml = `<p>${stem}</p>`
      }

      question.stem = `<div class=\"qml-stem\" data-copyright=\"jyeoo.com\">${stemHtml}</div>`
      question.answer = `<div class=\"qml-answer\" data-copyright=\"jyeoo.com\"><span class=\"qml-an-sq\"><span class=\"qml-an\">B</span></span><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>D</p></span></span><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>B</p></span></span><span class=\"qml-an-sq\"><span class=\"qml-an\"><p>B</p></span></span><span class=\"qml-an-sq\"><span class=\"qml-an qml-isop \">C</span></span></div>`
    }
    // 解析
    question.explanation = `<div class=\"qml-explanation\" style=\"line-height: 0.28rem;\" data-copyright=\"jyeoo.com\"><div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${
      explanation ? explanation : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${
      method ? method : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${
      discuss ? discuss : '无'
    }</div></div></div>`
  } else {
    // 拍照上传答案
    let stemHtml = ''

    if (stem.indexOf('MathJye') != -1 || stem.indexOf('quizPutTag') != -1) {
      stemHtml = `<p></p><fieldset style="margin-top:0.1rem;font-size:0.26rem">${stem}</fieldset>`
    } else {
      stemHtml = `<p>${stem}</p>`
    }

    question.stem = `<div class=\"qml-stem\" data-copyright=\"jyeoo.com\">${stemHtml}</div>`
    question.answer = `<div class=\"qml-answer\" data-copyright=\"jyeoo.com\"><span class=\"qml-an-sq\"><span class=\"qml-an\"><span>${displayAnswer}</span></span></span></div>`
    // 解析
    question.explanation = `<div class=\"qml-explanation\" style=\"line-height: 0.28rem;\" data-copyright=\"jyeoo.com\"><div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${
      explanation ? explanation : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${
      method ? method : '无'
    }</div></div><div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${
      discuss ? discuss : '无'
    }</div></div></div>`
  }

  return question
}
